#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：tools 
@File ：注册码生成器.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/11/27 上午9:48 
"""

from cryptography.fernet import Fernet
import json
from datetime import datetime, timedelta
import secrets
from tkinter import Tk, Label, Entry, Button, Text, messagebox


# 生成密钥并实例化Fernet类
def generate_key():
	return Fernet.generate_key()


# 保存密钥到config.json
def save_key_to_config(key):
	config = {"fernet_key": key.decode()}
	with open("config.json", "w") as config_file:
		json.dump(config, config_file)


# 加载密钥
def load_key_from_config():
	try:
		with open(CONFIG_FILE, "r") as config_file:
			config = json.load(config_file)
		return config["fernet_key"].encode()
	except FileNotFoundError:
		return None


# 注册码存储文件
LICENSE_FILE = "./config/encrypted_licenses.txt"
CONFIG_FILE = "./config/config.json"


# 生成注册码并设置有效期
def generate_license_code(expiration_days=30):
	license_code = secrets.token_hex(16)
	expiration_date = datetime.now() + timedelta(days=expiration_days)
	return license_code, expiration_date


# 加密注册码并保存到文件
def save_encrypted_license(license_code, expiration_date, cipher_suite):
	# 将注册码和有效期转换为字典
	licenses = {license_code: expiration_date.isoformat()}
	# 将字典转换为JSON字符串
	licenses_json = json.dumps(licenses)
	# 加密JSON字符串
	encrypted_licenses = cipher_suite.encrypt(licenses_json.encode())
	# 保存加密的注册码到文件
	with open(LICENSE_FILE, "wb") as file:
		file.write(encrypted_licenses)


# GUI界面
def create_gui():
	root = Tk()
	root.title("注册码生成器")
	root.geometry("400x300")  # 设置窗口大小为400x300

	# 检查config.json是否存在并加载密钥
	key = load_key_from_config()
	if key is None:
		key = generate_key()
		save_key_to_config(key)
	cipher_suite = Fernet(key)

	# 输入有效期的标签和输入框
	Label(root, text="输入注册码有效期（天）:").pack(pady=5)
	expiration_days_entry = Entry(root)
	expiration_days_entry.pack(pady=5)

	# 生成注册码按钮
	def on_generate_click():
		expiration_days = int(expiration_days_entry.get())
		license_code, expiration_date = generate_license_code(expiration_days)
		# 显示注册码和有效期
		output_text.delete('1.0', 'end')
		output_text.insert('1.0', f"Generated License Code: {license_code}\n")
		output_text.insert('end', f"Valid until: {expiration_date.strftime('%Y-%m-%d %H:%M:%S')}\n")
		save_encrypted_license(license_code, expiration_date, cipher_suite)

	generate_button = Button(root, text="生成注册码", command=on_generate_click)
	generate_button.pack(pady=10)

	# 显示注册码的文本区域
	output_text = Text(root, height=10, width=50)
	output_text.pack(pady=10)

	root.mainloop()


if __name__ == "__main__":
	create_gui()
